#!/bin/sh

## usage: music [-a]
#         music selector_name action [action_args...]

abspath() {
	echo "$(cd "$(dirname "$1")" >/dev/null||exit; pwd)/"
}

DATA_HOME=${XDG_DATA_HOME:-"$HOME/.local/share"}
XDG_DATA_DIRS=${XDG_DATA_DIRS:-/usr/local/share/:/usr/share/}
playlist="$DATA_HOME/music/playlist"

SELECTOR_DIRS="$(abspath "$0")${SELECTOR_DIRS}"

is_local() {
	scheme="${1%%:*}"
	[ "$scheme" = 'file' ]
}

exists() {
	[ -f "${1#*://}" ]
}

print_usage() {
	printf "
Usage:
\t%s [-a]
\t%s <selector_name> <action> [action_args...]

Control the music player

Options:
 -a\t\tappend to queue
 -h\t\tshow this help and quit

For more details see music(1) and music(8)\n" "$1" "$1"
}

emplace() {
	pid=$(cat ~/.local/share/play/pid 2>/dev/null)

	if [ "$pid" = '' ] || ! kill -0 "$pid" 2>/dev/null
	then
		mpv --input-ipc-server=/tmp/play-mpv-socket --idle --no-terminal --no-video 2>&1 >/dev/null &  # todo log
		pid=$!
		echo $pid > ~/.local/share/play/pid
	fi

	if [ "$1" = '' ]
	then
		mode="replace"
		echo >"$playlist"
	elif [ "$1" = '-a' ]
	then
		mode="append-play"
	fi

	# stdin entries must be URI; it is assumed, not checked
	songs=$(cat /dev/stdin)

	songs_head=$(echo "$songs" | head -n1)
	songs_tail=$(echo "$songs" | tail -n+2)

	is_idle=$(echo '{"command": ["get_property", "core-idle"]}' | socat - /tmp/play-mpv-socket | jq '.data' -r)
	is_active_idle=$(echo '{"command": ["get_property", "idle-active"]}' | socat - /tmp/play-mpv-socket | jq '.data' -r)

	uri=$(echo "$songs_head" | cut -d '' -f 2)
	if is_local "$uri" && ! exists "$uri"
	then
		printf "No such file %s\n" "$uri" >&2
	else
		reply=$(echo '{"command": ["loadfile", "'"$uri"'", "'"$mode"'"]}' | socat - /tmp/play-mpv-socket)
		echo "$songs_head" >>"$playlist"
		# todo print error
	fi

	if [ "$is_idle" = "true" ] && [ "$is_active_idle" = 'false' ] && [ "$mode" = "replace" ]
	then
		reply=$(echo '{"command": ["keypress", "PAUSE"]}' | socat - /tmp/play-mpv-socket)
		# todo print error
	fi

	echo "$songs_tail" | while read -r song
	do
		if [ "$song" ]
		then
			uri=$(echo "$song" | cut -d '' -f 2)
			if is_local "$uri" && ! exists "$uri"
			then
				printf "No such file %s\n" "$uri" >&2
			else
				reply=$(echo '{"command": ["loadfile", "'"$uri"'", "append"]}' | socat - /tmp/play-mpv-socket)
				echo "$song" >>"$playlist"
				# todo print error
			fi
		fi
	done
}

do_action() {
	selector_name="$1"
	action="$2"
	shift
	shift
	
	IFS=':'; for dir in $SELECTOR_DIRS
	do
		if [ -d "$dir/music/selectors" ] && ls "$dir/music/selectors" | grep "$selector_name" >/dev/null
		then
			selector="$dir/music/selectors/$selector_name"
			break
		fi
	done

	if [ "$selector" ]
	then
		"$selector/actions/$action" "$@"
	else
		echo "selector ‘$selector_name’ not found"
	fi
}


if [ "$1" = '-h' ]
then
	print_usage "$0"
elif [ "$1" = '-a' ] || [ "$1" = '' ]
then
	emplace "$1"
else
	do_action "$@"
fi
